﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using up7.db.database;
using up7.down3.model;
using up7.filemgr.app;

namespace up7.down3.biz
{
    public class fd_page_oracle : fd_page
    {
        public override String read(String pageIndex, String id)
        {
            int pageSize = 100;//每页100条数据
            int index = int.Parse(pageIndex);
            index = Math.Max(index, 1);//基于1
            int pageStart = ((index - 1) * pageSize) + 1;
            int pageEnd = index * pageSize;

            DBConfig cfg = new DBConfig();
            SqlExec se = cfg.se();
            var o = se.select("up7_files", "*", new SqlParam[] { new SqlParam("f_id", id) });
            //子目录
            if (o == null) o = se.select("up7_folders", "*", new SqlParam[] { new SqlParam("f_id", id) });

            string pathRoot = o.SelectToken("$..f_pathRel").ToString();
            var dirLen = pathRoot.Length;

            string sql = string.Format(@"select * from 
                                        (
                                            select rownum rn ,a.* from(select f_id,f_nameLoc,f_pathSvr,f_pathRel,f_lenLoc,f_sizeLoc,f_blockPath,f_blockSize from up7_files where f_pidRoot='{0}'
                                        ) a 
                                        where rownum <= {1} ) where rn >= {2}
                                        ", id, pageEnd, pageStart);

            List<DnFileInf> files = new List<DnFileInf>();
            DbHelper db = new DbHelper();
            using (var cmd = db.GetCommand(sql))
            {
                using (var r = db.ExecuteReader(cmd))
                {
                    while (r.Read())
                    {
                        var f       = new DnFileInf();
                        f.id        = Guid.NewGuid().ToString("N");
                        f.f_id      = r.GetString(1);//从1开始,0是行号
                        f.nameLoc   = r.IsDBNull(2)?string.Empty: r.GetString(1);//f_nameLoc
                        f.pathSvr   = r.GetString(3);
                        f.pathRel   = r.GetString(4);
                        f.pathRel   = f.pathRel.Substring(dirLen);
                        f.lenSvr    = r.GetInt64(5);
                        f.sizeSvr   = r.GetString(6);
                        f.blockPath = r.IsDBNull(7)?string.Empty: r.GetString(6);
                        f.blockSize = r.GetInt32(8);
                        files.Add(f);
                    }
                    r.Close();
                }
            }

            if (files.Count > 0) return JsonConvert.SerializeObject(files);
            return "";
        }
    }
}